﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Threading;
using System.Globalization;
using Barbar.UrlGuard.BL;

namespace Barbar.UrlGuard.Dal.Persist {
  internal class DataContextHolder : IDataContextHolder {
    private DataContext m_DataContext;
    private ILanguageObserver m_LanguageObserver;
    private ILogger m_Logger;

    public DataContextHolder(ILanguageObserver languageObserver, ILogger logger) {
      if (languageObserver == null)
        throw new ArgumentNullException("languageObserver");

      if (logger == null)
        throw new ArgumentNullException("logger");
      
      m_LanguageObserver = languageObserver;
      m_Logger = logger;
    }

    private IDataContextPersistor CreatePersistor() {
      string folder = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "WebMonitor");
      if (!Directory.Exists(folder))
        Directory.CreateDirectory(folder);
      string file = Path.Combine(folder, "Settings.xml");
      return new XmlDataContextPersistor(file, m_Logger);
    }

    #region IDataHolder Members

    public DataContext Context {
      get {
        if (m_DataContext == null) {
          m_DataContext = CreatePersistor().Load();
        }
        return m_DataContext;
      }
    }

    public void Persist() {
      if (m_DataContext == null) {
        m_DataContext = CreatePersistor().Load();
      }
      CreatePersistor().Persist(m_DataContext);
      if (Thread.CurrentThread.CurrentCulture.LCID != m_DataContext.LanguageID) {
        Thread.CurrentThread.CurrentCulture = new CultureInfo(m_DataContext.LanguageID);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(m_DataContext.LanguageID);
        m_LanguageObserver.FireLanguageChanged();
      }
    }

    #endregion
  }
}
